import React, { Component } from 'react'
import { connect } from 'react-redux'

import { Input, AutoComplete } from 'antd'

class Search extends Component {
    constructor(props) {
        super(props)
        this.state = {
            initOptions: [
            ], 
            options: [],
            value: ''
        }
    }

    componentDidMount() {
        let initOptions = []
        this.props.graphData.nodes.map(node => {
            initOptions.push({ value: node.name })
            return node
        })
        this.setState({
            initOptions: initOptions
        })
    }

    onSearch = (value) => {
        this.setState({
            value: value
        })
    }

    onSelect = (value, option) => {
        let focusNode = null
        for(let i = 0; i < this.props.graphData.nodes.length; i++) {
            if(this.props.graphData.nodes[i].name === value) {
                focusNode = this.props.graphData.nodes[i]
            }
        }
        this.focusOnNode(focusNode, this.props.graph)
    }

    focusOnNode = (node, graph) => {
        graph.centerAt(node.x, node.y, 1000)
        graph.zoom(8, 2000)
    }

    render() {
        let options = []
        let initOptions = []
        this.props.graphData.nodes.map(node => {
            initOptions.push({ value: node.name })
            return node
        })
        if(this.state.value !== '') {
            initOptions.map(initOption => {
                if(initOption.value.indexOf(this.state.value) === 0) {
                    options.push(initOption)
                }
                return initOption
            })
        }

        return (
            <div className="graph-robustness-search">
                <AutoComplete
                    style={{ width: 300 }}
                    options={options}
                    onSearch={this.onSearch}
                    onSelect={this.onSelect}
                >
                    <Input.Search size="large" placeholder="搜索节点..." />
                </AutoComplete>
            </div>
        )
    }
}


const mapStateToProps = (state) => ({
    graphData: state.robustness.graph
})


export default connect(mapStateToProps)(Search)
